<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 商店管理
 */
namespace app\ais\controller\store;
use app\ais\model\AisStoreWorker;
use app\common\facade\AliApi;
use app\common\model\SystemUser;
use app\ais\controller\Common;
use app\ais\model\AisCoupon;
use app\ais\model\AisStoreCate;
use app\ais\model\AisStore;
use app\ais\model\AisCouponUser;
use app\ais\model\AisOrder;
use app\ais\model\AisConfig;
use app\common\facade\Inform;
use think\helper\Time;
use think\facade\Request;
use think\facade\Validate;

class Index extends Common{

    public function initialize(){
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'商家管理','url'=>url("ais/store.index/index")]]);
    }

    /**
     * 列表
     */
    public function index(int $types = 0){
        $condition   = [];
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        $keyword = Request::param('keyword/s');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        if($types){
            $condition[] = ['is_lock','=',$types == 2 ? 1 : 0];
        }
        $view['lists']      = AisStore::where($this->mini_program)->where($condition)->order('is_top desc,sort desc,id desc')->paginate(20,false,['query' => ['types' => $types,'starttime' => $starttime,'endtime' => $endtime,'time'=>$time]]);
        $view['keyword']    = $keyword;
        $view['types']      = $types;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        return view()->assign($view);
    }


    /**
     * 好店预览
     */
    public function review(int $id){
        $condition['id'] = $id;
        $view['info']   = AisStore::where($condition)->find();
        if(!$view['info']){
            $this->error('内容不存在');
        }
        $view['user']   = AisStoreWorker::where($this->mini_program)->where(['store_id' => $id])->order('id desc')->select();
        $view['manage'] = SystemUser::where($this->mini_program)->where(['id' => $view['info']['manage_uid']])->find();
        $view['orders']  = AisOrder::where($this->mini_program)->where(['store_id'=>$id,'state' => 1])->order('id desc')->paginate(10,false,['query' => ['id' => $id]]);
        return view()->assign($view);
    }
    
    //编辑
    public function edit(){
        if(request()->isAjax()){
            $param = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'id'                => Request::param('id/d'),
                'manage_uid'        => Request::param('manage_uid/d',0),
                'cate_id'           => Request::param('cate_id/d',0),
                'cate_sid'          => Request::param('cate_sid/d',0),
                'province'          => Request::param('province/d'),
                'city'              => Request::param('city/d'),
                'district'          => Request::param('district/d'),
                'citycode'          => Request::param('citycode/d'),
                'name'              => Request::param('name/s'),
                'address'           => Request::param('address/s'),
                'longitude'         => Request::param('longitude/s'),
                'latitude'          => Request::param('latitude/s'),
                'telphone'          => Request::param('telphone/s'),
                'img'               => Request::param('img/s'),
                'imgs'              => Request::param('imgs/a'),
                'mch_id'            => Request::param('mch_id/s'),
                'tags'              => Request::param('tags/s'),
                'charge'            => Request::param('charge/f'),
            ];
            $validate = $this->validate($param,'Store.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $condition[] = ['manage_uid','=',$param['manage_uid']];
            if($param['id']){
                $condition[] = ['id','<>',$param['id']];
            }
            $store = AisStore::where($condition)->find();  
            if($store){
                return json(['code'=>0,'msg'=>'禁止绑定,设置的店长已属于['.$store->name.']的店长']);
            }
            $param['citypath'] = [
                'province' => $param['province'],
                'city'     => $param['city'],
                'district' => $param['district'],
            ];
            $store_id = AisStore::edit($param);
            return json(['code'=>200,'url'=>url('store/index',['cate_id' => $param['cate_id']]),'msg'=>'操作成功']);
        }else{
            $view['info']     = AisStore::where($this->mini_program)->where(['id' => $this->request->param('id/d')])->find();
            $view['cate']     = AisStoreCate::where($this->mini_program)->where(['parent_id' => 0])->field('name,id')->order('sort desc,id desc')->select();
            $view['setting']  = AisConfig::getConfig($this->member_miniapp_id);
            $view['cate_sub'] = [];
            if($view['info']){
                $view['cate_sub'] = AisStoreCate::where($this->mini_program)->where(['parent_id' => $view['info']->cate_id])->field('name,id')->order('sort desc,id desc')->select();
            }
            return view()->assign($view);
        }
    }
     
    /**
     * 排序
     */
    public function sort(){
        if(request()->isAjax()){
            $data = [
                'sort' => $this->request->param('sort/d'),
                'id'   => $this->request->param('id/d'),
            ];
            $validate = $this->validate($data,'Category.sort');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = AisStore::where(['id' => $data['id']])->update(['sort' => $data['sort']]);
            if($result){
                return json(['code'=>200,'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }
    }
    
    /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isTop(int $id){
        $result = AisStore::isTop($id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 

     /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = AisStore::isLock($id,$this->member_miniapp_id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 
   
    //删除
    public function delete(int $id){
        $coupon = AisCoupon::where($this->mini_program)->where(['store_id' => $id])->count();
        if($coupon){
            return json(['code'=>403,'msg'=>'请先删除好店优惠券']);
        }
        $couponUser =  AisCouponUser::where($this->mini_program)->where(['store_id' => $id])->count();
        if($couponUser){
            return json(['code'=>403,'msg'=>'请先删除用户已领优惠券']);
        }
        AisStore::where($this->mini_program)->where(['id' => $id])->delete();   //删除好店
        return json(['code'=>200,'msg'=>'操作成功']);
    }

    
    /**
     * 读取好店分类
     * @return void
     */
    public function storecate(int $cate_id){
        $cate = AisStoreCate::where(['member_miniapp_id' => $this->member_miniapp_id,'parent_id' => $cate_id])->field('id,name')->order('sort desc,id desc')->select(); 
        return json(['code'=>200,'msg'=>'成功','data' => $cate]);
    }
 
    /**
     *  根据地址位置转账
     * @return void
     */
    public function baidu($address){
        $view['address']  = $address;
        $this->view->engine->layout(false);
        return view()->assign($view);
    }   

    /**
     *  根据地址位置读取地址
     * @return void
     */
    public function maps($address){
        $rel = AliApi::address($address);
        if(!$rel){
            return enjson(0,'请确认是否帐号欠费');
        }
        $address = $rel['geocodes'][0];
        $location =  explode(',',$address['location']);
        return enjson(200,'成功',$location);
    }

    /**
     * 选择商家列表
     */
    public function selectStore($select_uid = 0){
        $condition = [];
        $condition[] = ['is_lock','=',0];
        $view['keyword'] = $this->request->param('keyword/s');
        if(!empty($view['keyword'])){
            $condition[] = ['name','like','%'.$view['keyword'].'%'];
        }
        $view['lists']      = AisStore::where($this->mini_program)->where($condition)->order('is_top desc,sort desc,id desc')->paginate(20);
        $view['input']      = $this->request->param('input');
        $view['select_uid'] = $select_uid;
        return view()->assign($view);
    }
   

    /**
     * 选择所属用户
     */
    public function selectUid(){
        $view['keyword'] = Request::param('keyword');
        $view['input']   = Request::param('input');
        $condition = [];
        if(!empty($view['keyword'])){
            if(Validate::isMobile($view['keyword'])){
                $condition[] = ['phone_uid','=',$view['keyword']];
            }else{
                $condition[] = ['nickname','like','%'.$view['keyword'].'%'];
            }
        }
        $view['list'] = SystemUser::where($this->mini_program)->where($condition)->whereNotIn('id',AisStore::where($this->mini_program)
                    ->column('manage_uid'))->order('id desc')
                    ->paginate(10,false,['query' => ['input' => $view['input'],'keyword' => $view['keyword']]]);
        return view()->assign($view);
    }


    /**
     * 给好店添加管理员
     */
    public function winUser(int $store_id){
        if(request()->isAjax()){
            $ids = Request::param('ids/s');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要关联的员工']);
            }
            $uid = (array)ids($ids,true);
            $worker_uid = AisStoreWorker::where($this->mini_program)->where(['uid' => $uid])->column('uid'); //查询添加的用户是否在其它点做员工
            $uid = array_diff($uid,$worker_uid);//如果存在就去重
            $data = [];
            foreach ($uid as $key => $value) {
                $data[$key]['member_miniapp_id'] = $this->member_miniapp_id;
                $data[$key]['uid']               = $value;
                $data[$key]['store_id']          = $store_id;
            }
            $result = AisStoreWorker::insertAll($data);
            if($result){
                //批量添加的员工为当前店铺的会员
                foreach ($data as $key => $value) {
                    //通知到申请者微信
                    Inform::sms($value['uid'],$this->member_miniapp_id,['title' =>'业务进展通知','type' => '身份变更','state' => '成功','content' =>'您的身份已变更为员工']);
                }
                return json(['code'=>200,'msg'=>'添加员工成功','data' =>[]]);
            }else{
                return json(['code'=>0,'msg'=>'添加员工失败']);
            }
        }else{
            //读好好店员工和好店老板的UID,做筛查排除
            $uid = AisStoreWorker::where($this->mini_program)->column('uid');       //好店员工
            $keyword  = Request::param('keyword');
            $condition  = [];
            $condition[] = ['id','NOT IN',$uid];
            if(!empty($keyword)){
                if(Validate::isMobile($keyword)){
                    $condition[] = ['phone_uid','=',$keyword];
                }else{
                    $condition[] = ['nickname','LIKE','%'.$keyword.'%'];
                }
            }
            $view['list']     = SystemUser::where($this->mini_program)->where($condition)->order('id desc')->paginate(20,false,['query' => ['store_id' => $store_id]]);
            $view['store_id'] = $store_id;
            $view['keyword']  = $keyword;
            return view()->assign($view);
        }
    }

    //删除员工
    public function delUser(int $id){
        $result = AisStoreWorker::where($this->mini_program)->where(['uid' => $id])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        }
    }

    /**
     * 设置好店收银员
     * @param integer $id 用户ID
     */
    public function isCashier(int $id){
        $result = AisStoreWorker::setWorker($id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    }
}